import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoSever_0603 {
    ServerSocket socket = null;

    public TcpEchoSever_0603(int port) throws IOException {
        this.socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true) {
            //分配服务员，相当于记录信息（即连接）
            Socket clientSocket = socket.accept();
            //processConnection(clientSocket);
            ExecutorService pool = Executors.newCachedThreadPool();
            pool.submit(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%s] 客户端：上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%s] 客户端：下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //客户端发起的请求必须以分隔符结尾。
                String request = scanner.next();
                //返回 用println，结尾自动加了换行，便于客户端读取！！！
                String response = process(request);
                printWriter.println(response);
                printWriter.flush(); //刷新缓冲区，及时传递
                System.out.printf("[%s:%d] req：%s，resp：%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoSever_0603 tcpEchoSever0603 = new TcpEchoSever_0603(9090);
        tcpEchoSever0603.start();
    }
}
